package com.jdew.thkj.activity;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.OnlineUpBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;

import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class OnlineUpgradeActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.super_no)
    TextView superNo;
    @Bind(R.id.gaoji_no)
    TextView gaojiNo;
    @Bind(R.id.phone)
    EditText phone;
    @Bind(R.id.mima)
    EditText mima;
    @Bind(R.id.cansee)
    ImageView cansee;
    @Bind(R.id.superview)
    LinearLayout superview;
    @Bind(R.id.gaojiview)
    LinearLayout gaojiview;
    @Bind(R.id.iv1)
    ImageView iv1;
    @Bind(R.id.iv2)
    ImageView iv2;
    @Bind(R.id.setting)
    Button setting;
    @Bind(R.id.nice_spinner)
    NiceSpinner spinner;
    @Bind(R.id.right)
    TextView right;
    private int type = 0;
    private String level = "2";
    private String activityId;
    private ArrayList<OnlineUpBean.DataBean> list = new ArrayList<>();
    private ArrayList<String> nameList = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    private String sessionId;
    private String seceret;
    private String message;

    @Override
    public int bindLayout() {
        return R.layout.activity_online_upgrade;
    }

    @Override
    public void initView(View view) {
        back.setVisibility(View.VISIBLE);
        right.setVisibility(View.VISIBLE);
        right.setText("升级记录");
        title.setText("在线升级");
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        back.setOnClickListener(this);
        cansee.setOnClickListener(this);
        gaojiview.setOnClickListener(this);
        superview.setOnClickListener(this);
        setting.setOnClickListener(this);
        right.setOnClickListener(this);
        spinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                activityId = list.get(position).getTypeId();
            }
        });
        getSessionId();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.right: {
                startActivity(UpgradeRecordActivity.class);
            }
            break;
            case R.id.superview: {
                level = "0";
                iv2.setImageResource(R.mipmap.check);
                iv1.setImageResource(R.mipmap.uncheck);
            }
            break;
            case R.id.gaojiview: {
                level = "2";
                iv1.setImageResource(R.mipmap.check);
                iv2.setImageResource(R.mipmap.uncheck);
            }
            break;
            case R.id.setting: {
                if (TextUtils.isEmpty(phone.getText())) {
                    ToastUtils.getInstance(this).showMessage("请输入手机号码");
                    return;
                } else if (TextUtils.isEmpty(mima.getText())) {
                    ToastUtils.getInstance(this).showMessage("请输入二级密码");
                    return;
                } else if (!RegexValidateUtils.checkCellphone(phone.getText().toString())) {
                    ToastUtils.getInstance(this).showMessage("请输入正确的手机号码");
                    return;
                }
                if (level.equals("0")) {
                    message = "此操作不可逆,确定为该惠员升级为超级教练吗？";
                } else if (level.equals("2")) {
                    message = "此操作不可逆,确定为该惠员升级为高级惠员吗？";
                }
                doUpgrade(message);
            }
            break;
            case R.id.cansee: {
                if (type == 0) {
                    cansee.setImageResource(R.mipmap.r_in);
                    mima.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    type = 1;
                } else {
                    cansee.setImageResource(R.mipmap.r_un);
                    mima.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    type = 0;
                }
                mima.setSelection(mima.getText().toString().length());
            }
            break;
            default:
                break;
        }
    }

    public void getGetRemainder() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetRemainder(sessionId, sp.getString("userId", ""), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Guid" + sp.getString("userId", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<OnlineUpBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(OnlineUpBean bean) {
                if (bean.getCode().equals("0")) {
                    if (null != bean && null != bean.getData()) {
                        list.clear();
                        nameList.clear();
                        gaojiNo.setText(bean.getNum());
                        superNo.setText(bean.getNumto());
                        for (int i = 0; i < bean.getData().size(); i++) {
                            list.add(bean.getData().get(i));
                            nameList.add(bean.getData().get(i).getTypeName() + "  高:" + bean.getData().get(i).getGNumber() + "  超:" + bean.getData().get(i).getCNumber());
                        }
                        activityId = list.get(0).getTypeId();
                        spinner.attachDataSource(nameList);
                    }
                }
            }
        });
    }

    public void getSessionId() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetSessionId(RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    sessionId = json.getString("message");
                    seceret = json.getString("data");
                    getGetRemainder();
                }
            }
        });
    }

    public void GetUserUpgrade() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("FrequencyType", activityId);
        map.put("NewPwd", mima.getText().toString().trim());
        map.put("Userlevel", level);
        map.put("UserPhone", sp.getString("userPhone", ""));
        map.put("UserUsePhone", phone.getText().toString().trim());
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetUserUpgrade(sessionId, map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "FrequencyType" + activityId + "NewPwd" + mima.getText().toString().trim() + "Userlevel" + level + "UserPhone" + sp.getString("userPhone", "") + "UserUsePhone" + phone.getText().toString().trim())).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(JSONObject json) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                doTit(json.getString("message"));
                getGetRemainder();
            }
        });
    }

    public void doUpgrade(String Message) {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage(Message)
                .setMessageGravity()
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (!RegexValidateUtils.isFastClick()) {
                            return;
                        }
                        GetUserUpgrade();
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    public void doTit(String Message) {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage(Message)
                .setMessageGravity()
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                })
                .setNegativeButton("取消", null).show();
    }

}
